<?php

namespace app\admin\controller;

use app\common\model\Category as CategoryModel;
use app\common\validate\Category as CategoryV;
use think\facade\View;

class Category extends Base
{
    /**
     * 导航列表
     */
    public function index()
    {
        $list = CategoryModel::with('photo')->order('sort desc,id asc')->paginate([
            'list_rows'     =>  20,
            'query'         =>  $this->get,
        ]);
        return View::fetch('', ['list' => $list]);
    }

    /**
     * 添加导航
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try {
                validate(CategoryV::class)->check($this->post);
                (new CategoryModel())->replace()->save($this->post);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '添加失败');
            }
            return $this->success('添加成功', 'index');
        }
        return View::fetch();
    }

    /**
     * 修改导航
     */
    public function edit()
    {
        $info = CategoryModel::find($this->get['id']);
        if ($this->request->isAjax()) {
            try {
                validate(CategoryV::class)->scene('edit')->check($this->post);
                $info->replace()->save($this->post);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '修改失败');
            }
            return $this->success('修改成功', 'index');
        }
        return View::fetch('', ['info' => $info]);
    }

    /**
     * 删除导航
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            try {
                CategoryModel::destroy($this->post['id']);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '删除失败');
            }
            return $this->success('删除成功', 'index');
        }
    }
}
